package org.shj.basic

import java.io.File

object ImplicitDemo {
  def main(args: Array[String]): Unit = {
    implicitClassDemo
    
    implicitParam
  }
  
  def implicitClassDemo{
    object Context{
      implicit class FileEnhancer(file: File){
        def read = println("read method in FileEnhancer")
      }
      implicit class Op(x: Int){
        def addSap(second: Int) = x + second
      }
    }
    //类的隐式转换。 当发现某个对象调用其本身没有的方法时，会查找当前是否存在以此对象为构造器的某个类具备该方法
    import Context._
    println(1.addSap(2)) // 会自动把 1 转化成 Op(1)
    println(new File("d:\\test").read)    
  }
  
  def implicitParam{
    abstract class Template[T]{
      def add(x: T, y: T) : T
    }
    
    abstract class SubTemplate[T] extends Template[T]{
      def unit: T
    }
    implicit object StringAdd extends SubTemplate[String]{
      override def add(x: String, y: String) = x concat y
      override def unit: String = ""
    }
    
    implicit object IntAdd extends SubTemplate[Int]{
      override def add(x: Int, y: Int) = x + y
      override def unit: Int = 0
    }
    
    def sum[T](xs: List[T])(implicit m: SubTemplate[T]): T = {
      if(xs.isEmpty) m.unit
      else m.add(xs.head, sum(xs.tail))
    }
    
    println("sum(List(1,2,3,4,5)): " + sum(List(1,2,3,4,5)))
    println("sum(List('Scala', 'Spark')):" + sum(List("Scala", "Spark")))
  }
}